package club.gskj.gulimall.ware.service.impl;

import club.gskj.common.utils.R;
import club.gskj.gulimall.ware.feign.MemberFeignService;
import club.gskj.gulimall.ware.vo.FreightAddrVo;
import club.gskj.gulimall.ware.vo.MemberAddressVo;
import com.alibaba.fastjson.TypeReference;
import org.omg.CORBA.ObjectHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.logging.Level;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import club.gskj.common.utils.PageUtils;
import club.gskj.common.utils.Query;

import club.gskj.gulimall.ware.dao.WareInfoDao;
import club.gskj.gulimall.ware.entity.WareInfoEntity;
import club.gskj.gulimall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        // 条件检索
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key)
                        .or()
                        .like("name", key)
                        .or()
                        .like("address", key)
                        .or()
                        .like("areacode", key);
            });
        }

        IPage<WareInfoEntity> page = this.page(new Query<WareInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public FreightAddrVo getgetFreight(Long addrId) {

        FreightAddrVo freightAddrVo = new FreightAddrVo();

        R info = memberFeignService.getMemberReceiveAddres(addrId);
        if (info.getCode() == 0) {
            MemberAddressVo data = info.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
            });
            // 计算运费信息
            if (data != null) {
                // TODO 可以直接调用第三方接口服务，查询所地区的运费信息
                String phone = data.getPhone();
                // 这里模拟假 运费数据
                String substring = phone.substring(phone.length() - 1, phone.length());
                freightAddrVo.setFreight(new BigDecimal(substring));
                freightAddrVo.setMemberAddressVo(data);
                return freightAddrVo;
            }
        }
        return null;
    }

}
